package com.kanshu.ksgb.fastread.doudou.common.business.ad

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.Xutils
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*

/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/17 15:29
 *
 * @author EvanHe
 * @version 3.0
 */
class OwnAdUtils {

    companion object {

        private fun jumpOwnUrl(adConfig: ADConfigBean, activity: Activity) {
            adConfig.ad_image_jump?.let {
                val uri = Uri.parse(it)
                val value = uri.getQueryParameter("is_jump_wx_client")
                if (TextUtils.equals("1", value)) {
                    try {
                        val i = Intent(Intent.ACTION_VIEW, uri)
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        activity.startActivity(i)
                    } catch (e: Exception) {
                        val map = mutableMapOf<String, String>()
                        map["url"] = it
                        map["title"] = "广告"
                        ARouterUtils.toActivity(ARouterConfig.COMMON_H5, map)
                    }

                } else {
                    val map = mutableMapOf<String, String>()
                    map["url"] = it
                    map["title"] = "广告"
                    ARouterUtils.toActivity(ARouterConfig.COMMON_H5, map)
                }
            }
        }

        fun fetchSplashAd(activity: Activity, container: ViewGroup?, adConfig: ADConfigBean, skipContainer: TextView?, adStyle: Int, layout: Int, adListener: BaseAdListener?) {
            val adContainer = container ?: FrameLayout(activity)
            if (TextUtils.isEmpty(adConfig.ad_image_url)) {
                if (adStyle != AdStyleBean.SPLASH_STYLE) {
                    AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                } else {
                    adListener?.onAdLoadFailed()
                }
                return
            }
            var imageView: ImageView? = null
            val layoutParams = when (adStyle) {
                AdStyleBean.SPLASH_STYLE -> {
                    if (adListener is SplashAdListener) {
                        adListener.isShowSkipView(true)
                    }
                    var time = 5
                    skipContainer?.text = String.format(activity.getString(R.string.ad_click_to_skip), time)
                    val timer = Timer(true)
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            AndroidSchedulers.mainThread().scheduleDirect {
                                time--
                                if (time == 0) {
                                    adListener?.onADClosed()
                                } else {
                                    skipContainer?.text = String.format(activity.getString(R.string.ad_click_to_skip), if (time > 0) time else 0)
                                }
                            }
                        }
                    }, 1000, 1000)
                    if (adListener is SplashAdListener) {
                        adListener.onFastADClosed(timer)
                    }
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
                }
                AdStyleBean.BANNER_STYLE
                -> FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(activity, 50f))
                AdStyleBean.BOOK_COVER_STYLE
                -> {
                    val rootView = LayoutInflater.from(activity).inflate(layout, container, false)
                    imageView = rootView.findViewById(R.id.cover) as ImageView
                    val title = rootView.findViewById(R.id.book_title) as TextView?
                    val desc = rootView.findViewById(R.id.desc) as TextView?
                    title?.text = adConfig.title ?: ""
                    desc?.text = adConfig.description ?: ""
                    rootView.setOnClickListener {
                        AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                        if (adStyle != AdStyleBean.SPLASH_STYLE) {
                            AdUtils.addFullExposureTime(activity, adContainer, skipContainer, adConfig.ad_position.toInt(), adStyle, layout, adListener, ADConfigBean.TYPE_OWN)
                        }
                        jumpOwnUrl(adConfig, activity)
                    }
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
                }
                AdStyleBean.IMAGE_TEXT_STYLE
                -> {
                    val view = View.inflate(activity, R.layout.layout_360_ad_container, null) as View
                    val title = view.findViewById(R.id.ad_360_title) as TextView
                    imageView = view.findViewById(R.id.ad_chapter_container) as ImageView
                    title.text = adConfig.title ?: ""
                    FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, activity.resources.getDimensionPixelSize(R.dimen.px_720))
                }
                else
                -> FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
            }
            if (imageView == null) {
                imageView = ImageView(activity)
                imageView.scaleType = ImageView.ScaleType.FIT_XY
            }
            val options = RequestOptions()
                    .fitCenter()
            var context: Context = activity
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (activity.isDestroyed) {
                    context = Xutils.getContext()
                }
            }
            Glide.with(context)
                    .load(adConfig.ad_image_url) // 图片地址
                    .apply(options) // 参数
                    .into(object : SimpleTarget<Drawable>() {
                        override fun onLoadCleared(placeholder: Drawable?) {
                            super.onLoadCleared(placeholder)
                        }
                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            Log.i("own_ad", "onLoadFailed")
                            if (adStyle != AdStyleBean.SPLASH_STYLE) {//开屏广告不需要保底广告
                                AdUtils.fetchAdFailed(activity, adContainer, adConfig, adStyle, layout, adListener)
                            } else {
                                adListener?.onAdLoadFailed()
                            }
                        }

                        override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                            Log.i("own_ad", "success $resource")
                            imageView.setImageDrawable(resource)
                            if (resource is Animatable) {
                                resource.start()
                            }
                            when (adStyle) {
                                AdStyleBean.BOOK_COVER_STYLE
                                -> adListener?.onAdLoadSucceeded(getRootView(imageView))
                                AdStyleBean.IMAGE_TEXT_STYLE
                                -> {
                                    AdUtils.destroyAd(adContainer)
                                    adContainer.removeAllViews()
                                    adContainer.addView(getRootView(imageView), 0, layoutParams)
                                    adListener?.onAdLoadSucceeded(adContainer)
                                }
                                else -> {
                                    AdUtils.destroyAd(adContainer)
                                    adContainer.removeAllViews()
                                    adContainer.addView(imageView, 0, layoutParams)
                                    adListener?.onAdLoadSucceeded(adContainer)
                                }
                            }
                            AdUtils.pVUVAd(AdPresenter.AD_SHOW, adConfig)
                            adContainer.setOnClickListener {
                                AdUtils.pVUVAd(AdPresenter.AD_CLICK, adConfig)
                                if (adStyle != AdStyleBean.SPLASH_STYLE) {
                                    AdUtils.addFullExposureTime(activity, adContainer, skipContainer, adConfig.ad_position.toInt(), adStyle, layout, adListener, ADConfigBean.TYPE_OWN)
                                }
                                jumpOwnUrl(adConfig, activity)
                            }
                        }
                    })
        }
    }
}